package com.ieds.core.conf;

import com.ieds.common.toolkit.Constant;
import com.ieds.core.model.KUser;
import com.ieds.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor{

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Object attribute = request.getSession().getAttribute(Constant.SESSION_ID);
		String uri = request.getRequestURI();
		String loginYesOrNo = Constant.LOGIN_YESORNO;
		//登陆请求不能被拦截
		if (!uri.contains("view/loginUI.shtml") && !uri.contains("index/login.shtml")) {
			//判断session中是否有值？
			if (attribute == null) {
				if (Boolean.parseBoolean(loginYesOrNo)){
					//不登录，直接跳转首页
					KUser kUser = new KUser();
					kUser.setuAccount("admin");
					kUser.setuPassword("admin");
					KUser u = userService.login(kUser);
					request.getSession().setAttribute(Constant.SESSION_ID,u);
					request.getSession().setMaxInactiveInterval(60*60);
					response.sendRedirect(request.getContextPath()+"/view/indexUI.shtml");
				}else{
					response.sendRedirect(request.getContextPath() + "/view/loginUI.shtml");
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}